#include "digital.h"
#include "gpio.h"
#include <stdlib.h>

static int env_gpio_read(const char *label_env, const char *line_env, const char *al_env,
                         const char *def_label, unsigned def_line, int def_active_low,
                         const char *consumer, int *val)
{
    const char *label = getenv(label_env);
    const char *line_s = getenv(line_env);
    int active_low = def_active_low;
    const char *al = getenv(al_env);
    if (al && *al) active_low = atoi(al) ? 1 : 0;
    unsigned line = def_line;
    if (line_s && *line_s) line = (unsigned)atoi(line_s);
    if (!label || !*label) label = def_label;
    return gpio_read_value(label, line, active_low, val, consumer);
}

int read_key(int index, int *val)
{
    // 默认：KEY1=PF9，KEY2=PF8，KEY3=PF7
    if (index == 1) return env_gpio_read("KEY1_GPIO_LABEL", "KEY1_GPIO_LINE", "KEY1_ACTIVE_LOW",
                                         "GPIOF", 9, 1, "key1", val);
    if (index == 2) return env_gpio_read("KEY2_GPIO_LABEL", "KEY2_GPIO_LINE", "KEY2_ACTIVE_LOW",
                                         "GPIOF", 8, 1, "key2", val);
    if (index == 3) return env_gpio_read("KEY3_GPIO_LABEL", "KEY3_GPIO_LINE", "KEY3_ACTIVE_LOW",
                                         "GPIOF", 7, 1, "key3", val);
    return -1;
}

int read_photo_switch(int *val)
{
    return env_gpio_read("PHOTO_GPIO_LABEL", "PHOTO_GPIO_LINE", "PHOTO_ACTIVE_LOW",
                         "GPIOE", 15, 1, "photo", val);
}

int read_flame(int *val)
{
    // 许多火焰传感器检测到火焰时输出高电平，这里将默认改为高有效（active_low=0）。
    // 如需相反逻辑，可在运行时设置 FLAME_ACTIVE_LOW=1 覆盖。
    return env_gpio_read("FLAME_GPIO_LABEL", "FLAME_GPIO_LINE", "FLAME_ACTIVE_LOW",
                         "GPIOF", 5, 0, "flame", val);
}

int read_infrared(int *val)
{
    // NOTE: 部分板卡的人体红外默认高电平为“有人”。将默认改为 active_low=0
    // 如需相反逻辑，可在运行时设置 IR_ACTIVE_LOW=1 覆盖。
    return env_gpio_read("IR_GPIO_LABEL", "IR_GPIO_LINE", "IR_ACTIVE_LOW",
                         "GPIOF", 12, 0, "infrared", val);
}
